/*
 * Created by Ganlin.Wu on 16-9-14 下午5:03
 * Copyright (c) 2016. All rights reserved.
 */

package com.wgl.support.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

import com.wgl.support.R;

/**
 * Created by Ganlin.Wu on 2016/9/14.
 */
public class CustomProgressBar extends View {

    private static final int DEFAULT_WIDTH_DP = 100;
    private static final int DEFAULT_HEIGHT_DP = 35;

    private int mTextSize;

    private int mLoadColor;

    private int mStopColor;


    private Paint mBackgroundPaint;
    private Paint mTextPaint;

    private int mProgressColor;
    private String mProgressText;
    private Rect mTextRect;


    private int mMaxValue = 100;
    private int mValue = 0;

    public CustomProgressBar(Context context) {
        super(context);
        init(context, null);
    }

    public CustomProgressBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void initAttrs(Context context, AttributeSet attrs) {
        if (attrs != null) {
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomProgressBar);
            mTextSize = (int) a.getDimension(R.styleable.CustomProgressBar_text_size, sp2px(12));
            mLoadColor = a.getColor(R.styleable.CustomProgressBar_load_color, Color.parseColor("#40c4ff"));
            mStopColor = a.getColor(R.styleable.CustomProgressBar_stop_color, Color.parseColor("#ff9800"));
            mMaxValue = a.getInt(R.styleable.CustomProgressBar_max, 100);
            a.recycle();
        }
    }

    private void init(Context context, AttributeSet attrs) {
        initAttrs(context, attrs);

        mBackgroundPaint = new Paint();
        mBackgroundPaint.setAntiAlias(true);

        mTextPaint = new Paint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(mTextSize);

        mTextRect = new Rect();

        mProgressColor = mLoadColor;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        int width = widthSize;
        int height = heightSize;
        switch (widthMode) {
            case MeasureSpec.EXACTLY:
                width = widthSize;
                break;
            case MeasureSpec.AT_MOST:
                width = dp2px(DEFAULT_WIDTH_DP);
                break;
        }
        switch (heightMode) {
            case MeasureSpec.EXACTLY:
                height = heightSize;
                break;
            case MeasureSpec.AT_MOST:
                height = dp2px(DEFAULT_HEIGHT_DP);
                break;
        }
        setMeasuredDimension(width, height);
    }

    private int dp2px(float value) {
        float scale = getContext().getResources().getDisplayMetrics().density;
        return Math.round(value * scale);
    }

    private int sp2px(float value) {
        float scale = getContext().getResources().getDisplayMetrics().scaledDensity;
        return Math.round(value * scale);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawBorder(canvas);
        drawProgress(canvas);
        drawProgressText(canvas);
        drawColorProgressText(canvas);
    }

    /**
     * 画矩形边框
     * @param canvas
     */
    private void drawBorder(Canvas canvas) {
        mBackgroundPaint.setStyle(Paint.Style.STROKE);
        mBackgroundPaint.setColor(mProgressColor);
        mBackgroundPaint.setStrokeWidth(dp2px(1));
        canvas.drawRect(0, 0, getWidth(), getHeight(), mBackgroundPaint);
    }

    /**
     * 根据进度填充颜色
     * @param canvas
     */
    private void drawProgress(Canvas canvas) {
        float len = getProgressWidth();
        mBackgroundPaint.setStyle(Paint.Style.FILL);
        mBackgroundPaint.setColor(mProgressColor);
        mBackgroundPaint.setStrokeWidth(0);
        canvas.drawRect(0, 0, len, getHeight(), mBackgroundPaint);
    }

    /**
     * 画进度提示文字
     * @param canvas
     */
    private void drawProgressText(Canvas canvas) {
        mTextPaint.setColor(mProgressColor);
        mProgressText = getProgressText();
        mTextPaint.getTextBounds(mProgressText, 0, mProgressText.length(), mTextRect);
        int tWidth = mTextRect.width();
        int tHeight = mTextRect.height();
        float x = (getMeasuredWidth() - tWidth) / 2f;
        float y = (getMeasuredHeight() + tHeight) / 2f;
        canvas.drawText(mProgressText, x, y, mTextPaint);
    }

    /**
     * 进度与文字重叠部分的文字变色
     * @param canvas
     */
    private void drawColorProgressText(Canvas canvas) {
        mTextPaint.setColor(Color.WHITE);
        mProgressText = getProgressText();
        mTextPaint.getTextBounds(mProgressText, 0, mProgressText.length(), mTextRect);
        int tWidth = mTextRect.width();
        int tHeight = mTextRect.height();
        float x = (getMeasuredWidth() - tWidth) / 2f;
        float y = (getMeasuredHeight() + tHeight) / 2f;

        float len = getProgressWidth();
        if(len > x){
            canvas.save(Canvas.CLIP_SAVE_FLAG);
            canvas.clipRect(0, 0, len, getMeasuredHeight());
            canvas.drawText(mProgressText, x, y, mTextPaint);
            canvas.restore();
        }
    }

    protected String getProgressText() {
        StringBuilder sb = new StringBuilder();
        float len = mValue / (float) mMaxValue;
        if (len < 1) {
            sb.append("正在下载...");
            sb.append(String.format("%.2f", len * 100) + "%");
        } else {
            sb.append("下载完成！");
        }
        return sb.toString();
    }

    protected float getProgressWidth() {
        return mValue / (float) mMaxValue * getMeasuredWidth();
    }

    public void setProgress(int value) {
        mValue = value;
        invalidate();
    }

}
